import { getUserProfile, updateUserProfile, useAppDispatch, updateUserPhoto, logout } from '@/store/index'
import { Toast, List, Popup, DatePicker, Dialog, Button } from 'antd-mobile'
import classNames from 'classnames'
import { useInitialState } from '@/hooks/useInitialState'
import styles from './index.module.scss'
import React, { useRef, useState } from 'react'
import EditInput from './components/EditInput/index'
import EditList from './components/EditList/index'
import { useNavigate } from 'react-router-dom'
import dayjs from '@/plugin/dayjs/index'

const { Item } = List
interface InputState {
  visible: boolean
  type: 'name' | 'intro'
}
interface ListState {
  visible: boolean
  type: 'gender' | 'photo'
}
type PopupType = 'name' | 'intro' | 'gender' | 'photo' | 'birthday'

export default function ProfileEdit() {
  const navigate = useNavigate()
  const { userProfile } = useInitialState(getUserProfile, 'loginSlice')
  const dispatch = useAppDispatch()

  // 姓名和简介弹层控制
  const [showInput, setShowInput] = useState<InputState>({
    visible: false,
    type: 'name'
  })

  // 关闭姓名和简介弹层
  function hidePopup(type: PopupType) {
    if (type === 'name' || type === 'intro') {
      setShowInput({
        visible: false,
        type: type
      })
    } else if (type === 'gender' || type === 'photo') {
      setShowList({
        visible: false,
        type: type
      })
    } else if (type === 'birthday') {
      onBirthdyHide()
    }
  }

  // 完成更新
  async function onUpdate(type: PopupType, value: string) {
    if (type === 'photo') {
      fileRef.current?.click()
      return
    }
    Toast.show({
      icon: 'loading',
      duration: 0
    })
    // 发送请求修改
    await dispatch(updateUserProfile({ type: value }))
    // 提示修改成功
    Toast.show({
      content: '修改成功',
      icon: 'success'
    })
    // 关闭弹层
    hidePopup(type)
  }

  // 性别和头像弹层
  const [showList, setShowList] = useState<ListState>({ visible: false, type: 'gender' })

  // 文件选择框ref
  const fileRef = useRef<HTMLInputElement>(null)
  // 文件域变化事件
  async function onChangePhoto(e: React.ChangeEvent<HTMLInputElement>) {
    Toast.show({
      icon: 'loading',
      duration: 0
    })
    const file = e.target.files![0]
    const fd = new FormData()
    fd.append('photo', file)
    await dispatch(updateUserPhoto(fd))
    Toast.show({
      content: '修改头像成功',
      icon: 'success'
    })
    // 关闭弹层
    hidePopup('photo')
    fileRef.current!.value = ''
  }

  // 生日日期选择器
  const [showBirthday, setShowBirthday] = useState(false)
  // 打开日期选择器
  function onBirthdayShow() {
    setShowBirthday(true)
  }
  // 关闭日期选择器
  function onBirthdyHide() {
    setShowBirthday(false)
  }
  // 确认日期
  function onBirthdayConfirm(value: Date) {
    onUpdate('birthday', dayjs(value).format('YYYY-MM-DD'))
  }

  // 退出登录
  function logoutFn() {
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要退出吗？',
      onConfirm() {
        dispatch(logout())
        navigate('/login')
      }
    })
  }
  return (
    <>
      <div className={styles.root}>
        <div className="content">
          <div className="wrapper">
            {/* 列表 */}
            <List className="profile-list">
              {/* 列表项 */}
              <Item
                extra={
                  <span className="avatar-wrapper">
                    <img width={24} height={24} src={userProfile.photo} alt="" />
                  </span>
                }
                arrow
                onClick={() => setShowList({ visible: true, type: 'photo' })}
              >
                头像
              </Item>
              <Item
                arrow
                extra={userProfile.name}
                onClick={() => setShowInput({ visible: true, type: 'name' })}
              >
                昵称
              </Item>
              <Item
                arrow
                extra={
                  <span className={classNames('intro', userProfile.intro && 'normal')}>
                    {userProfile.intro || '未填写'}
                  </span>
                }
                onClick={() => setShowInput({ visible: true, type: 'intro' })}
              >
                简介
              </Item>
            </List>

            <List className="profile-list">
              <Item
                arrow
                extra={userProfile.gender === 0 ? '男' : '女'}
                onClick={() => setShowList({ visible: true, type: 'gender' })}
              >
                性别
              </Item>
              <Item arrow extra={userProfile.birthday} onClick={onBirthdayShow}>
                生日
              </Item>
            </List>
          </div>
          <div className="logout">
            <Button className="btn" onClick={logoutFn}>
              退出登录
            </Button>
          </div>
        </div>
        {/* 修改名字，简介弹层 */}
        <Popup destroyOnClose visible={showInput.visible} position="right" bodyStyle={{ width: '100vw' }}>
          <EditInput hideInput={hidePopup} type={showInput.type} onUpdate={onUpdate}></EditInput>
        </Popup>
        {/* 修改性别，头像弹层 */}
        <Popup visible={showList.visible} position="bottom">
          <EditList type={showList.type} hideList={hidePopup} onUpdate={onUpdate}></EditList>
        </Popup>
        {/* 照片选择文件域 */}
        <input type="file" ref={fileRef} hidden onChange={onChangePhoto} />
        {/* 生日日期选择器 */}
        <DatePicker
          visible={showBirthday}
          value={new Date(userProfile.birthday)}
          title="选择年月日"
          min={new Date('1900-01-01')}
          max={new Date()}
          onCancel={onBirthdyHide}
          onConfirm={(value) => onBirthdayConfirm(value)}
        ></DatePicker>
      </div>
    </>
  )
}
